package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.wallet.subview

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.EditText
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import org.json.JSONObject

interface IProofCameroonWalletAddDialogListener {
    fun onClick(type: String, mobile: String)
}

class ProofCameroonWalletAddDialog(var onItemClick: IProofCameroonWalletAddDialogListener? = null) :
    DialogFragment() {

    private lateinit var list: RecyclerView
    private lateinit var mobile: EditText
    private lateinit var mobileConfirm: EditText
    private lateinit var confirm: TextView
    private lateinit var close: ImageView
    private lateinit var adapter: ProofCameroonWalletAddDialogAdapter

    private var walletInfo: JSONObject? = null
    private var typeList: MutableList<JSONObject> = mutableListOf()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        return inflater.inflate(R.layout.view_cameroon_proof_wallet_add_dialog, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog?.setCancelable(true)
        dialog?.setCanceledOnTouchOutside(true)

        confirm = view.findViewById(R.id.confirm)
        list = view.findViewById(R.id.list)
        close = view.findViewById(R.id.close)
        mobile = view.findViewById(R.id.mobile)
        mobileConfirm = view.findViewById(R.id.mobileConfirm)

        initializeView()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Dialog)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onStart() {
        super.onStart()

        dialog?.window?.let {
            it.attributes.gravity = Gravity.CENTER
            it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        }

        mobile.text = null
        mobileConfirm.text = null

        adapter.notifyDataSetChanged()
    }

    private fun initializeView() {
        confirm.setOnClickListener {
            var gType = ""
            for (item in typeList) {
                val selected = item.optBoolean("isSelected", false)
                if (selected) {
                    gType = item.optString("value")
                }
            }
            val hasSelected = gType.isNotBlank()
            if (!hasSelected) {
                Toast.makeText(context, "Veuillez choisir un opérateur*", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val mobile1 = mobile.text.toString()
            val hasMobile = mobile1.isNotBlank()
            if (!hasMobile) {
                Toast.makeText(context, "Numéro de téléphone*", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val mobile2 = mobileConfirm.text.toString()
            val hasMobileConfirm = mobile2.isNotBlank()
            if (!hasMobileConfirm) {
                Toast.makeText(
                    context,
                    "Confirmer le numéro de téléphone à nouveau*",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }

            val hasMobileSame = (mobile1 == mobile2)
            if (!hasMobileSame) {
                Toast.makeText(
                    context,
                    "Confirmer le numéro de téléphone à nouveau*",
                    Toast.LENGTH_SHORT
                ).show()
                return@setOnClickListener
            }

            onItemClick?.onClick(type = gType, mobile = mobile1)
        }

        close.setOnClickListener {
            dismiss()
        }

        adapter =
            ProofCameroonWalletAddDialogAdapter(
                typeList,
                object : IProofCameroonWalletAddDialogAdapterListener {
                    @SuppressLint("NotifyDataSetChanged")
                    override fun onClick(position: Int) {
                        for (index in 0 until typeList.size) {
                            val item = typeList[index]
                            if (position == index) {
                                item.put("isSelected", true)
                            } else {
                                item.put("isSelected", false)
                            }
                        }
                        adapter.notifyDataSetChanged()
                    }
                })
        list.layoutManager = LinearLayoutManager(context)
        list.adapter = adapter

        setTypeList(ProjectApplication.mWalletChannels)
    }

    private fun setTypeList(list: List<JSONObject>) {
        typeList.clear()
        for (index in 0 until list.size) {
            val item = list[index]
            item.put("isSelected", false)
            typeList.add(item)
        }
    }
}

interface IProofCameroonWalletAddDialogAdapterListener {
    fun onClick(position: Int)
}

class ProofCameroonWalletAddDialogAdapter(
    var dataList: List<JSONObject>,
    var onClick: IProofCameroonWalletAddDialogAdapterListener? = null
) :
    RecyclerView.Adapter<ProofCameroonWalletAddDialogAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_cameroon_proof_wallet_add_dialog_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val contentBg: RelativeLayout = view.findViewById(R.id.contentBg)
        private val icon: ImageView = view.findViewById(R.id.icon)
        private val type: TextView = view.findViewById(R.id.type)
        private val ext: ImageView = view.findViewById(R.id.ext)

        @SuppressLint("SetTextI18n")
        fun bindData(item: JSONObject, position: Int) {
            type.text = item.optString("desc")

            val isSelected = item.optBoolean("isSelected", false)
            if (isSelected) {
                contentBg.setBackgroundResource(R.drawable.bg_proof_wallet_type_selected)
                type.setTextColor(Color.parseColor("#000000"))
                type.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                ext.setImageResource(R.drawable.pic_proof_wallet_add_checkbox_hl)

            } else {
                contentBg.setBackgroundResource(R.drawable.bg_proof_wallet_type_unselect)
                type.setTextColor(Color.parseColor("#C9CDD9"))
                type.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                ext.setImageResource(R.drawable.pic_proof_wallet_add_checkbox_nor)
            }

            val logo = item.optString("logo")
            if (logo.isNotBlank()) {
                icon.visibility = View.VISIBLE
                Glide.with(icon).load(logo).into(icon)
            } else {
                icon.visibility = View.GONE
            }

            contentBg.setOnClickListener {
                onClick?.onClick(position)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data, position)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}